package com.lawyer.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.lawyer.entity.Config;
import com.lawyer.entity.Coupon;
import com.lawyer.entity.MoneyFlows;
import com.lawyer.entity.User;
import com.lawyer.entity.Withdrawal;
import com.lawyer.model.BindingReq;
import com.lawyer.model.Message;
import com.lawyer.model.MessageConstant;
import com.lawyer.repository.ConfigRepository;
import com.lawyer.repository.CouponRepository;
import com.lawyer.repository.MoneyFlowsRepository;
import com.lawyer.repository.UserRepository;
import com.lawyer.repository.WithdrawalRepository;

@RestController
@RequestMapping(value = "/agent")
@Api(tags = "代理推广")
@SuppressWarnings("all")
public class AgentManageController {

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private MoneyFlowsRepository moneyFlowsRepository;

	@Autowired
	private ConfigRepository configRepository;

	@Autowired
	private CouponRepository couponRepository;
	
	@Autowired
	private WithdrawalRepository withdrawalRepository;

	@ApiOperation(httpMethod = "POST", value = "用户绑定代理", notes = "用户绑定代理")
	@RequestMapping(value = "/binding", method = RequestMethod.POST)
	public HttpEntity<?> binding(@RequestBody BindingReq bindingReq) {
		Message msg = new Message();
		try {

			User agent = userRepository.findOne(bindingReq.getAgentId());

			User user = userRepository.findOne(bindingReq.getUserId());

			if (user == null || agent == null) {
				// msg.setMessage("代理或用户不存在");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}

			if (StringUtils.isNotEmpty(user.getAgentId())) {
				// msg.setMessage("已绑定代理,不能重复绑定");
				return new ResponseEntity<>(msg, HttpStatus.OK);

			}

			if ("0".equals(agent.getUserType())) {
				// msg.setMessage("不是代理,不能绑定");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}

			if ("1".equals(user.getUserType())) {
				// msg.setMessage("代理不能绑定代理用户");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}
			user.setAgentId(agent.getId());
			user.setAgentCode(bindingReq.getAgentId());
			user.setBindingDate(new Date());
			userRepository.save(user);

		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "GET", value = "分享群记录", notes = "分享一个群，记录一次,分享累计三次，代理会获取一笔奖励")
	@RequestMapping(value = "/shareGroup", method = RequestMethod.GET)
	public HttpEntity<?> shareGroup(String userId) {
		Message msg = new Message();
		boolean flag = false;
		try {
			User user = userRepository.findOne(userId);

			if (user != null) {
				// 更新分享次数
				user.setShareCount(user.getShareCount() + 1);
				if (user.getShareCount() >= 3 && user.getDedication() == false) {
					Config configDay = configRepository.findByName("CouponValidity");// 有效期时长
					user.setDedication(true);
					// 累计三次获取一张免费的优惠卷
					Coupon coupon = new Coupon();
					coupon.setUserId(userId);
					coupon.setDescription("电话免费咨询一次");
					coupon.setTime(1);
					coupon.setIsUsed(false);
					coupon.setIsExpire(false);
					// 优惠卷过期时间
					coupon.setStartDate(new Date());

					Calendar c = Calendar.getInstance();
					c.add(Calendar.DAY_OF_MONTH, Integer.valueOf(configDay.getValue()));
					Date endDate = c.getTime();
					coupon.setEndDate(endDate);
					couponRepository.save(coupon);
					flag = true;
				}
				userRepository.save(user);

			}

			// 代理奖励
			if (user.getAgentId() != null) {
				User agent = userRepository.findOne(user.getAgentId());// 代理
				if (agent != null) {
					if (flag) {
						// 累计三次代理奖励3元
						Config config = configRepository.findByName("AgentCommission");// 分享群代理奖励5元
						agent.setBalance(agent.getBalance() + Double.valueOf(config.getValue()));
						userRepository.save(agent);
						// 保存变更记录
						MoneyFlows flow = new MoneyFlows();
						flow.setTypeFlow(1);
						flow.setUserId(agent.getId());
						flow.setUserName(agent.getNickName());
						flow.setPhone(agent.getPhone());
						flow.setUserType(agent.getUserType());
						flow.setChangeMoney(Double.valueOf(config.getValue()));
						flow.setDescription("推广奖励");
						moneyFlowsRepository.save(flow);
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	
	@ApiOperation(httpMethod = "POST", value = "代理提现", notes = "代理提现")
	@RequestMapping(value = "/withdrawal", method = RequestMethod.POST)
	public HttpEntity<?> withdrawal(@RequestBody Withdrawal request) {
		Message msg = new Message();
		try {
			User user = userRepository.findOne(request.getUserId());
			if (user != null) {
				
				if (request.getAmount() <100) {
					msg.setCode(MessageConstant.FAILED_CODE);
					msg.setMessage("提现最低金额100元");
					return new ResponseEntity<>(msg, HttpStatus.OK);
				}
				
				if (request.getAmount() > user.getBalance()) {
					msg.setCode(MessageConstant.FAILED_CODE);
					msg.setMessage("超过可提现最大金额");
					return new ResponseEntity<>(msg, HttpStatus.OK);
				}
			
				user.setBalance(user.getBalance() - request.getAmount());
				userRepository.save(user);
				
				//保存提现表 
				request.setStauts(1);//提现中
				request.setNickName(user.getNickName());
				request.setPhone(user.getPhone());
				request.setHeaderIco(user.getHeaderIco());
				request.setUserJob("代理");
				withdrawalRepository.save(request);
				
				// 保存变更记录
				MoneyFlows flow = new MoneyFlows();
				flow.setTypeFlow(1);
				flow.setUserId(request.getUserId());
				flow.setUserName(user.getNickName());
				flow.setPhone(user.getPhone());
				flow.setUserType("1");
				flow.setChangeMoney(0 - request.getAmount());
				flow.setDescription("提现");
				moneyFlowsRepository.save(flow);
			} else {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("账号不存在");
			}

		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}
	
}
